package com.steve.summary.seata.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.steve.summary.seata.entity.Storage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @Author: STEVE
 * @Description: 库存数据访问层
 * @since: 2025-07-08
 */
@Mapper
public interface StorageMapper extends BaseMapper<Storage> {

    /**
     * 根据商品id查询
     *
     * @param productId 商品id
     * @return
     */
    @Select("SELECT * FROM storage WHERE product_id = #{productId}")
    Storage selectByProductId(@Param("productId") String productId);

    /**
     * 扣减库存
     *
     * @param productId 商品id
     * @param count     扣减数量
     * @return
     */
    @Update("UPDATE storage SET residue = residue - #{count}, used = used + #{count} WHERE product_id = #{productId} AND residue >= #{count}")
    int deductStock(@Param("productId") String productId, @Param("count") Integer count);

    /**
     * 恢复库存
     *
     * @param productId 商品id
     * @param count     恢复数量
     * @return
     */
    @Update("UPDATE storage SET residue = residue + #{count}, used = used - #{count} WHERE product_id = #{productId}")
    int restoreStock(@Param("productId") String productId, @Param("count") Integer count);

    /**
     * 批量更新库存
     *
     * @param storages 库存集合
     * @return
     */
    int batchUpdateStock(@Param("list") List<Storage> storages);

}
